from django_redis import get_redis_connection
from rest_framework import serializers

from oauth.utils import check_access_token
from users.models import User
from .models import OAuthQQUser


class OAuthQQUserSerializer(serializers.Serializer):

    mobile = serializers.RegexField(regex='1[3-9]\d{9}',label='手机号',required=True)
    password = serializers.CharField(label='密码',required=True)
    sms_code = serializers.CharField(max_length=6,min_length=6,required=True)
    access_token = serializers.CharField()

    def validate(self, attrs):

        #1、验证 access_token
        access_token = attrs.get('access_token')
        openid = check_access_token(access_token)

        if openid is None:
            raise serializers.ValidationError('绑定时效过期')

        #添加openid，传递给 calidated_data
        attrs['openid']=openid

        #2、验证短信验证码
        #2.1获取用户提交
        sms_code = attrs.get('sms_code')
        mobile = attrs.get('mobile')
        #2.2获取redis的
        redis_conn = get_redis_connection('code')
        redis_sms_code = redis_conn.get('sms_%s' % mobile)
        if redis_sms_code is None:
            raise serializers.ValidationError('短信验证码已过期')
        #2.3比对
        if redis_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码错误')

        #3、判断手机号是否注册
        #根据手机号查询用户
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            #说明次手机号没有注册
            pass
        else:
            #说明次手机号已经注册
            if not user.check_password(attrs.get('password')):
                raise serializers.ValidationError('密码不正确')

            attrs['user']=user

        return attrs




    """
    数据的流向
    data --> attrs --> validated_data
    """

    def create(self, validated_data):

        user = validated_data.get('user')
        openid = validated_data.get('openid')

        if user is None:
            #说明 没有注册，我们需要手动创建一个用户
            user=User.objects.create(
                username=validated_data.get('mobile'),
                mobile=validated_data.get('mobile'),
                password=validated_data.get('password'),

            )
            user.set_password(validated_data.get('password'))
            user.save()

        qquser = OAuthQQUser.objects.create(
            user=user,
            openid=openid
        )
        return qquser


























